<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Ruby Threads: Ruby Study Notes - Best Ruby Guide, Ruby Tutorial</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="description" content="Ruby Study Notes - Best Ruby Guide, Ruby Tutorial" />
<meta name="keywords" content="ruby threads,ruby thread tutorial" />
<meta name="Distribution" content="Global" />
<meta name="author" content="Satish Talim / Original design: Erwin Aligam - ealigam@gmail.com" />
<meta name="copyright" content="Satish Talim 2007 and beyond..." />
<meta name="verify-v1" content="rFu86se+IkbtF+bH8mgJBKwU5HnKaSd8Ghw9umXQOkM=" />
<meta name="robots" content="index,follow" />
<meta http-equiv="Expires" content="0" />
<meta name="revisit-after" content="1 days" />
<link rel="stylesheet" href="/images/NewOrange.css" type="text/css" />
<link rel="stylesheet" href="/images/syntaxhighlighter.css" type="text/css" />
<link rel="icon" type="image/ico" href="/images/favicon.ico" />
<!-- Google +1 button code -->
<link rel="canonical" href="/satishtalim/ruby_threads.html" />
<script type="text/javascript" src="https://apis.google.com/js/plusone.js"></script>
<!-- Google Analytics code -->
<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-59044-10']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>
<!-- Google Analytics code ends -->
</head>

<body>
<!-- wrap starts here -->
<div id="wrap">

    <div id="header">

        <h1 id="logo">Ruby<span class="orange">Learning.github.io</span></h1>
        <h2 id="slogan">Helping Ruby Programmers become Awesome!</h2>

    </div>

    <div id="menu">
        <ul>
            <li><a href="/" title="Home page for rubylearning.github.io">Home</a></li>
            <li><a href="/satishtalim/tutorial.html" title="Get started Learning Ruby here...">Tutorial</a></li>
            <li><a href="/download/downloads.html" title="Download this tutorial as an eBook">Downloads</a></li>
            <li><a href="/other/testimonials.html" title="People around the world who benefited from this site">Testimonials</a></li>
            <li><a href="/other/certification.html" title="Get certified in Ruby">Certification</a></li>
            <li><a href="/satishtalim/ruby_guide.html" title="Ruby Guide, Mentor">Mentor</a></li>
            <li><a href="https://blog.rubylearning.github.io/" title="Ruby blog of Learning Ruby site">Blog</a></li>
            <li><a href="/satishtalim/tutorial.html" title="Online Ruby Course">Online Course</a></li>
            <li><a href="http://ruby-challenge.rubylearning.github.io/" title="Ruby Programming Challenge for Newbies">Challenge</a></li>
            <li><a href="/satishtalim/about.html" title="Information about Satish Talim">About</a></li>
        </ul>
    </div>

    <!-- content-wrap starts here -->
    <div id="content-wrap">

            <div id="main">

                <div id="main-inner"><a name="TemplateInfo"></a>
                <h1>Ruby Threads</h1>

                <p class="post-footer align-right">
                  <strong>
                    <a href="/satishtalim/ruby_socket_programming.html">&lt;Socket Programming | </a>
                    <a href="/satishtalim/tutorial.html">TOC | &gt;</a>
                  </strong>
                </p>

                <p>Let us have a quick look at Threads in Ruby. A <em>thread of execution</em> is a sequence of Ruby statements that run (or appear to run) in parallel with the main sequence of statements that the interpreter is running. Threads are implemented within the Ruby interpreter. That makes the Ruby threads completely portable - they don't rely on the operating system. At the same time, you don't get certain benefits from having native threads. This means that you may experience thread starvation (that's where a low-priority thread doesn't get a chance to run). If you manage to get your threads deadlocked, the whole process may grind to a halt. And if some thread happens to make a call to the operating system that takes a long time to complete, all threads will hang until the interpreter gets control back. Finally, if your machine has more than one processor, Ruby threads won't take advantage of that fact - because they run in one process, and in a single native thread, they are constrained to run on one processor at a time. Nevertheless Ruby threads are an efficient and lightweight way to achieve parallelism in your code.</p>

                <p>Let us study the following code:</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                # p070thread.rb
                x = Thread.new { sleep 0.1; print "x"; print "y"; print "z" }
                a = Thread.new { print "a"; print "b"; sleep 0.2; print "c" }
                x.join # Let the threads finish before
                a.join # main thread exits...
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>Here's the output:</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                >ruby p070thread.rb
                abxyzc>Exit code: 0
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>New threads are created with the <strong>Thread.new</strong> call. It is given a block that contains the code to be run in a new thread. The newly created thread will exit when the block exits. The <strong>Kernel.sleep</strong> method is used to suspend the current thread for duration seconds (which may be any number, including a <strong>Float</strong> with fractional seconds). The method returns the actual number of seconds slept (rounded). Zero arguments causes <strong>sleep</strong> to sleep forever. When you create a thread, it can access any variables that are within scope at that point. However, any local variables that are then created within the thread are entirely local to that thread. You can pass any number of arguments into the block via <strong>Thread.new</strong>.</p>

                <p>Why do we call <strong>join</strong> on each of the threads we created? When a Ruby program terminates, all threads are killed, regardless of their states. However, you can wait for a particular thread to finish by calling that thread's <strong>Thread.join</strong> method. The calling thread will block until the given thread is finished. By calling <strong>join</strong> on each of the requestor threads, you can make sure that all two requests have completed before you terminate the main program.</p>

                <p>The <strong>Thread</strong> class has several class methods that serve various purposes. The <strong>Thread.main</strong> method returns a reference to the main thread, which spawns the others. The <strong>Thread.list</strong> method returns an array of <strong>Thread</strong> objects for all threads that are either runnable or stopped. The <strong>Thread.current</strong> method returns the currently executing thread.</p>

                <p>The program so far:</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                puts Thread.main
                puts ""
                t1 = Thread.new {sleep 100}
                Thread.list.each {|thr| p thr }
                puts "Current thread = " + Thread.current.to_s
                puts ""
                puts Thread.main
                puts ""
                t1 = Thread.new {sleep 100}
                Thread.list.each {|thr| p thr }
                puts "Current thread = " + Thread.current.to_s
                puts ""

                t2 = Thread.new {sleep 100}
                Thread.list.each {|thr| p thr }
                puts Thread.current
                puts ""
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>The <strong>Thread.kill</strong>, <strong>Thread.pass</strong>, <strong>Thread.exit</strong>, <strong>Thread.start</strong> and <strong>Thread.stop</strong> methods are used to control the execution of threads (often from inside or outside). The <strong>Thread.kill</strong> method causes the given thread to exit. The <strong>Thread.pass</strong> method invokes the thread scheduler to pass execution to another thread. The <strong>Thread.exit</strong> method terminates the currently running thread and schedules another thread to be run. If this thread is already marked to be killed, <strong>Thread.exit</strong> returns the Thread. If this is the main thread, or the last thread, exit the process.</p>

                <p>The complete program:</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                puts Thread.main
                puts ""
                t1 = Thread.new {sleep 100}
                Thread.list.each {|thr| p thr }
                puts "Current thread = " + Thread.current.to_s
                puts ""

                t2 = Thread.new {sleep 100}
                Thread.list.each {|thr| p thr }
                puts Thread.current
                puts ""

                Thread.kill(t1)
                Thread.pass                          # pass execution to t2 now
                t3 = Thread.new do
                  sleep 20
                  Thread.exit                        # exit the thread
                end
                Thread.kill(t2)                      # now kill t2
                Thread.list.each {|thr| p thr }

                # now exit the main thread (killing any others)
                Thread.exit
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>The <strong>Thread.start</strong> method is basically the same as <strong>Thread.new</strong>. The <strong>Thread.stop</strong> method stops execution of the current thread, putting it into a "sleep" state, and schedules execution of another thread.</p>

                <p>The instance method thr.<strong>run</strong> wakes up thr, making it eligible for scheduling. The other instance method thr.<strong>terminate</strong> is a synonym for <strong>Thread.exit</strong>. Note that there is no instance method <strong>stop</strong>, so a thread can stop itself but not another thread.</p>

                <p>An example of the need for thread exclusion involves an electronic banking application. Suppose one thread is processing a transfer of money from a savings account to a checking account (an account which allows the holder to write checks against deposited funds), and another thread is generating monthly reports to be sent out to customers. Without proper exclusion, the report-generation thread might read the customer's account data after funds had been been subtracted from savings but before they had been added to checking.<br /><br /><strong><a href="http://ruby-doc.org/core-2.2.0/Mutex.html">Mutex</a></strong> (short for "mutual exclusion") is a core class in Ruby 2 and is part of the standard library. It is common to use the <strong>synchronize</strong> method of the <strong>Mutex</strong> class and associate a block with it. <strong>synchronize</strong> locks the <strong>Mutex</strong>, runs the code in the block, and then unlocks the <strong>Mutex</strong> in an <strong>ensure</strong> clause so that exceptions are properly handled. Here is a simple model of our bank account example, using a <strong>Mutex</strong> object to synchronize thread access to shared account data.</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                # mutexsyncex.rb
                require 'thread'  # For Mutex class in Ruby 1.8

                # A BankAccount has a name, a checking amount, and a savings amount
                class BankAccount
                  def initialize(name, checking, savings)
                    @name,@checking,@savings = name,checking,savings
                    @lock = Mutex.new  # For thread safety
                  end

                  # Lock account and transfer money from savings to checking
                  def transfer_from_savings(x)
                    @lock.synchronize {
                      @savings -= x
                      @checking += x
                    }
                  end

                  # Lock account and report current balances
                  def report
                    @lock.synchronize {
                      "#@name\nChecking: #@checking\nSavings: #@savings"
                    }
                  end
                end
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p style="background-color: #FAFAFA; padding: 5px; margin-top: 20px; font-size: 65%;"><strong>Note</strong>: The Ruby Logo is Copyright (c) 2006, Yukihiro Matsumoto. I have made extensive references to information, related to Ruby, available in the public domain (wikis and the blogs, articles of various <span style="font-weight: bold;" title="Click Gurus on the menu above">Ruby Gurus</span>), my acknowledgment and thanks to all of them. Much of the material on <a href="/">rubylearning.github.io</a> and in the course at <a href="http://rubylearning.org/">rubylearning.org</a> is drawn <strong>primarily</strong> from the <strong>Programming Ruby book</strong>, available from <a href="http://pragprog.com/titles/ruby3/programming-ruby-3">The Pragmatic Bookshelf</a>.</p>

                <p class="post-footer align-right">
                  <strong>
                    <a href="/satishtalim/ruby_socket_programming.html">&lt;Socket Programming | </a>
                    <a href="/satishtalim/tutorial.html">TOC | &gt;</a>
                  </strong>
                </p>

            </div>
            <!-- main inner ends here -->
        </div>

            <div id="rightbar">

            </div>

    <!-- content-wrap ends here -->
    </div>

<!-- wrap ends here -->
</div>

<!-- footer starts here -->
<div id="footer">
    <!-- CHANGE THE FOOTER -->
    <p>&copy; 2006-2021 <strong>rubylearning.github.io - A Ruby Tutorial</strong>&nbsp;&nbsp;Page Updated: 5th Jan. 2021 | Design: <a href="mailto:ealigam@gmail.com">Erwin Aligam</a> | Valid: <a href="http://validator.w3.org/check/referer">XHTML</a> | <a href="http://jigsaw.w3.org/css-validator/check/referer">CSS</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="/">Home</a> | <a href="/privacy.html">Privacy</a> | <a href="/sitemap.html">Sitemap</a></p>
</div>

<!-- footer ends here -->

<!-- SyntaxHighlighter code -->
<script src="/js/shCore.js" type="text/javascript"></script>
<script src="/js/shBrushRuby.js" type="text/javascript"></script>
<script type="text/javascript">
dp.SyntaxHighlighter.HighlightAll('code');
</script>
<!-- SyntaxHighlighter code -->
</body>
</html>
